package com.yanqu.road.server.manger.activity.yearMaster;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.game.config.StrengthConfig;
import com.yanqu.road.entity.activity.yearMaster.GridDetail;
import com.yanqu.road.entity.activity.yearMaster.YearMasterBoss;
import com.yanqu.road.entity.activity.yearMaster.YearMasterBossStateConfig;
import com.yanqu.road.entity.activity.yearMaster.YearMasterConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.logic.activity.YearMasterLogic;
import com.yanqu.road.logic.bussiness.activity.YearMasterBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.YearMasterPb;
import com.yanqu.road.logic.rank.RankListModel;
import com.yanqu.road.pb.yearMaster.YearMasterProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.yearMaster.YearMasterModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.ActivityRankMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class YearMasterMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(YearMasterMgr.class.getName());

    public static ActivityInfo activityInfo = null;

    public static YearMasterActivityConfig yearMasterActivityConfig = new YearMasterActivityConfig();
    //boss信息
    private static YearMasterBoss yearMasterBoss;

    private static Object lockObject = new Object();

    private static RandomHelper random = new RandomHelper();

    public static RandomHelper getRandom() {
        return random;
    }

    public static YearMasterActivityConfig getYearMasterActivityConfig() {
        return yearMasterActivityConfig;
    }


    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void reloadActivityInfo() {
        loadActivity();
    }

    private static void loadActivity() {
        getLogger().info("reload yearMaster activity start");
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.YearMasterActivity.getValue());
        ActivityInfo inTimeActivity = null;
        for (ActivityInfo ac : activityInfoList) {
            if (ac.getType() == eActivityType.YearMasterActivity.getValue()) {
                inTimeActivity = ac;
                break;
            }
        }
        if (inTimeActivity != null) {
            loadActivityConfig(inTimeActivity);
            playerReloadActivity();
        }

        getLogger().info("reload yearMaster activity end");
    }


    /**
     * 获取跨服活动数据
     */
    public static void getCrossActivityInfo() {
        if (activityInfo != null && ActivityMgr.activityInShowTime(activityInfo)) {
            YearMasterProto.CrossYearMasterNotifyInfoReqMsg.Builder builder = YearMasterProto.CrossYearMasterNotifyInfoReqMsg.newBuilder();
            builder.setActivityId(activityInfo.getActivityId());
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C2_CROSS_YEAR_MASTER_NOTIFY, builder));
        }
    }

    /**
     * 加载配置 覆盖过期活动配置
     *
     * @param inTimeActivity
     */
    private static void loadActivityConfig(ActivityInfo inTimeActivity) {

        try {
            YearMasterActivityConfig tempConfig = new YearMasterActivityConfig();
            //加载boss血量配置
            Map<Integer, YearMasterConfig> yearMasterBossConfig = YearMasterBussiness.getYearMasterBossConfig(inTimeActivity.getActivityId());
            String param = inTimeActivity.getParam6();
            String[] stateConfigs = param.split("\\|");
            int index = 0;
            Map<Integer, YearMasterBossStateConfig> yearMasterStateMap = new ConcurrentHashMap<>();
            for (String stateConfig : stateConfigs) {
                String[] config = stateConfig.split(";");
                YearMasterBossStateConfig cf = new YearMasterBossStateConfig();
                cf.setState(index++);
                cf.setBloodPercent(Integer.parseInt(config[0]));
                cf.setAdditionTypeId(Integer.parseInt(config[1]));
                cf.setAdditionPercent(Integer.parseInt(config[2]));
                yearMasterStateMap.put(cf.getState(), cf);
            }

            tempConfig.setStateHpMap(YearMasterLogic.pareStateHpMap(yearMasterBossConfig, yearMasterStateMap));
            //初始格子
            Map<Integer, Integer> initUserGridConfig = new ConcurrentHashMap<>();
            initUserGridConfig.put(3, 1);
            initUserGridConfig.put(4, 1);
            initUserGridConfig.put(5, 1);
            initUserGridConfig.put(9, 1);
            initUserGridConfig.put(10, 1);
            initUserGridConfig.put(11, 1);
            initUserGridConfig.put(15, 1);
            initUserGridConfig.put(16, 1);
            initUserGridConfig.put(17, 1);
            initUserGridConfig.put(19, 1);
            initUserGridConfig.put(20, 1);
            initUserGridConfig.put(21, 2);
            initUserGridConfig.put(22, 2);
            initUserGridConfig.put(23, 2);
            initUserGridConfig.put(7, 3);
            initUserGridConfig.put(8, 3);
            initUserGridConfig.put(13, 3);
            initUserGridConfig.put(14, 3);
            initUserGridConfig.put(18, 3);

            tempConfig.setInitUserGridConfig(initUserGridConfig);
            //基础权重
            //param5 1;200;-10;-40|2;200;-10;-40|3;200;-10;-40|4;200;-10;-40|   格子类型;格子基础权重;格子斜的权重影响;格子相连权重影响
            Map<Integer, GridDetail> newBaseGridWeightMap = new ConcurrentHashMap<>();
            String param5 = inTimeActivity.getParam5();
            String[] configs = param5.split("\\|");
            for (String stateConfig : configs) {
                String[] config = stateConfig.split(";");
                if (config.length != 4) {
                    continue;
                }
                GridDetail cf = new GridDetail();
                cf.setGridType(Integer.parseInt(config[0]));
                cf.setWeight(Integer.parseInt(config[1]));
                cf.setLeanReduce(Integer.parseInt(config[2]));
                cf.setLinkReduce(Integer.parseInt(config[3]));
                newBaseGridWeightMap.put(cf.getGridType(), cf);
            }

            tempConfig.setBaseGridWeightMap(newBaseGridWeightMap);

            // 分数对应
            // param3     xxx-1;50|2;100|4;300|   消除个数|分数
            Map<Integer, Integer> newScoreMap = new ConcurrentHashMap<>();
            String param3 = inTimeActivity.getParam3();
            configs = param3.split("-")[1].split("\\|");
            for (String scoreConfig : configs) {
                String[] config = scoreConfig.split(";");
                newScoreMap.put(Integer.parseInt(config[0]), Integer.parseInt(config[1]));
            }
            tempConfig.setScoreMap(newScoreMap);

            //体力配置 300|600|6|1;1|4;4-30000       上限|恢复周期秒|恢复点|普通场消耗;倍数|高级场消耗;倍数 -
            StrengthConfig newStrengthConfig = new StrengthConfig();
            String[] param4s = inTimeActivity.getParam4().split("-");

            String[] strength = param4s[0].split("\\|");
            newStrengthConfig.setMaxStrength(Integer.valueOf(strength[0]));
            newStrengthConfig.setSecends(Integer.valueOf(strength[1]));
            newStrengthConfig.setAddStrength(Integer.valueOf(strength[2]));

            tempConfig.setStrengthConfig(newStrengthConfig);
            tempConfig.setHighOpenScore(Long.parseLong(param4s[1]));

            //消耗配置
            String[] normalConfig = strength[3].split(";");
            tempConfig.setNormalPowerConsume(Integer.parseInt(normalConfig[0]));
            tempConfig.setNormalScoreMultiple(Integer.parseInt(normalConfig[1]));


            String[] highConfig = strength[4].split(";");
            tempConfig.setHighPowerConsume(Integer.parseInt(highConfig[0]));
            tempConfig.setHighScoreMultiple(Integer.parseInt(highConfig[1]));

            if (param4s.length >= 3) {
                tempConfig.setFastUnlockVipLevel(Integer.parseInt(param4s[2]));
                String[] fastConfig = strength[5].split(";");
                tempConfig.setFastPowerConsume(Integer.parseInt(fastConfig[0]));
                tempConfig.setFastScoreMultiple(Integer.parseInt(fastConfig[1]));
            } else {
                tempConfig.setFastUnlockVipLevel(Integer.MAX_VALUE);
                tempConfig.setFastPowerConsume(16);
                tempConfig.setFastScoreMultiple(16);
            }

            GoodsInfo eggGoods = GoodsMgr.getGoodsById(eItemId.YEAR_MASTER_EGG.getValue());
            if (eggGoods != null) {
                // 10|0|0|0
                tempConfig.setRestoreBaseStrength(eggGoods.getParamList().get(0).intValue());
            }

            //本服/跨服  积分排行条件
            Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap = NormalActivityMgr.getActivityConditionInfoMap(inTimeActivity.getActivityId());

            if (activityConditionInfoMap.containsKey(eGamePlayerEventType.YearMasterScoreCrossRank.getValue())) {
                tempConfig.setScoreRankType(eGamePlayerEventType.YearMasterScoreCrossRank.getValue());
            } else if (activityConditionInfoMap.containsKey(eGamePlayerEventType.YearMasterScoreRank.getValue())) {
                tempConfig.setScoreRankType(eGamePlayerEventType.YearMasterScoreRank.getValue());
            }

            //清除旧的boss数据
            synchronized (lockObject) {
                if(yearMasterBoss != null && yearMasterBoss.getActivityId() != inTimeActivity.getActivityId()) {
                    yearMasterBoss = null;
                }
            }
            yearMasterActivityConfig = tempConfig;
            activityInfo = inTimeActivity;
            //请求跨服boss数据
            getCrossActivityInfo();
        } catch (Exception e) {
            logger.error("loadActivityYearMasterConfig error");
            activityInfo = null;
        }

    }

    private static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(action -> {
            action.getModule(YearMasterModule.class).syncActivity();
        });
    }


    public static int getYearMasterUserRank(long userId,int crossRank) {
        //排名处理
        ActivityInfo openActivityInfo = getActivityInfo();
        if (openActivityInfo != null && ActivityHelper.activityInShowTime(openActivityInfo)) {
            int conditionType = yearMasterActivityConfig.getScoreRankType();
            boolean isCrossRank = ActivityHelper.conditionTypeIsCrossRank(conditionType);
            if (isCrossRank) {//跨服活动
                return crossRank;
            } else {
                RankListModel rankListModel = ActivityRankMgr.getActivityRankListModel(openActivityInfo.getActivityId(), conditionType);
                if (null != rankListModel) {
                    return rankListModel.unlockGetMyRank(userId);
                }
            }
        }
        return -1;
    }

//----------------------------------------送财相关---------------------------------------------------------------------

    /**
     * 送礼参数
     * param3 银两系数1|银两系数2|元宝系数1|元宝系数2 - xxxxx
     *
     * @return
     */
    public static List<String> getActivityDisperseGoldParam() {
        return StringUtils.stringToStringList(activityInfo.getParam3().split("-")[0], "\\|");
    }

    /**
     * 领取飞箭送礼奖励
     *
     * @param earnSpeed 领取奖励的玩家赚速
     * @return Property
     */
    public static Property getDisperseGoldReward(BigInteger earnSpeed) {
        if (activityInfo == null) {
            return null;
        }
        List<String> paramList = getActivityDisperseGoldParam();
        //银两奖励
        int totalSilver = random.next(Integer.valueOf(paramList.get(0)), Integer.valueOf(paramList.get(1)));
        BigInteger silver = earnSpeed.multiply(BigInteger.valueOf(totalSilver));
        //元宝奖励
        int ingots = random.next(Integer.parseInt(paramList.get(2)), Integer.valueOf(paramList.get(3)));
        Property property = new Property();
        property.addProperty(GameConfig.GAME_MONEY_SILVER, silver);
        property.addProperty(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(ingots));
        return property;
    }


    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static void setActivityInfo(ActivityInfo activityInfo) {
        YearMasterMgr.activityInfo = activityInfo;
    }
//----------------------------------------------boss相关---------------------------------------------------


    /**
     * 1 跨服boss状态阶段变更推送  bPushAll=true  2 跨服攻击boss 回包 bPushAll=false
     *
     * @param bossInfo
     * @param bPushAll
     */
    public static void updateBossInfo(YearMasterProto.YearMasterBossInfo bossInfo, boolean bPushAll) {

        if (yearMasterBoss == null) {
            initYearMasterBoss(false);
        }

        YearMasterProto.YearMasterBossInfo.Builder pushInfo = bossInfo.toBuilder();
        synchronized (lockObject) {
            if (yearMasterBoss.getActivityId() == bossInfo.getActivityId() &&
                    yearMasterBoss.getCurrentBlood() > bossInfo.getCurrentBlood()) {
                //下发最新的数据
                if (bPushAll) {
                    pushInfo = YearMasterPb.parseBossInfo(yearMasterBoss);
                }
            } else {
                yearMasterBoss.setActivityId(bossInfo.getActivityId());
                yearMasterBoss.setBossLevel(bossInfo.getBossLevel());
                yearMasterBoss.setCurrentBlood(bossInfo.getCurrentBlood());
                yearMasterBoss.setState(bossInfo.getBossState());
                yearMasterBoss.setTotalBlood(bossInfo.getTotalBlood());
                yearMasterBoss.setLastLvBlood(bossInfo.getBossLastLvBlood());
            }
        }

        //logger.info("updateBossInfo bPushAll:" + bPushAll + " hp:" + yearMasterBoss.getTotalBlood() + " chp " + yearMasterBoss.getCurrentBlood() + " state " + yearMasterBoss.getState() + "  lv:" + yearMasterBoss.getBossLevel() + " lhp " + yearMasterBoss.getLastLvBlood());
        //同步boss状态变更
        if (bPushAll) {
            List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();

            //boss成就数据
            playerList.forEach(gamePlayer -> {
                gamePlayer.notifyListener(eGamePlayerEventType.YearMasterBossState.getValue(), yearMasterBoss);
            });

            //同步boss信息
            for (GamePlayer gamePlayer : playerList) {
                gamePlayer.sendPacket(ClientProtocol.U_YEAR_MASTER_BOSS_SYNC, pushInfo);
            }
        }
    }


    /**
     * 初始化本服boss数据
     */
    private static void initYearMasterBoss(boolean crossReq) {
        synchronized (lockObject) {
            if (activityInfo != null && yearMasterBoss == null) {
                yearMasterBoss = new YearMasterBoss();
                yearMasterBoss.setCurrentBlood(0);
                yearMasterBoss.setBossLevel(1);
                yearMasterBoss.setState(0);
                yearMasterBoss.setTotalBlood(0);
                yearMasterBoss.setActivityId(activityInfo.getActivityId());
                if (crossReq) {
                    //拉取跨服boss
                    getCrossActivityInfo();
                }
            }
        }
    }

    public static YearMasterBoss getYearMasterBoss() {
        if (yearMasterBoss == null) {
            initYearMasterBoss(true);
        }
        return yearMasterBoss;
    }

    public static void setYearMasterBoss(YearMasterBoss yearMasterBoss) {
        YearMasterMgr.yearMasterBoss = yearMasterBoss;
    }

    //---------------------------------------------- 游戏逻辑---------------------------------------------------

    /**
     * 获取配置格子
     *
     * @param type 0单倍，1四倍，2十六倍
     */
    public static List<GridDetail> getConfigGridList(int type) {
        List<GridDetail> list = new ArrayList<>(yearMasterActivityConfig.getRow() * yearMasterActivityConfig.getColumn());
        //初始空格子
        initGrid(list);
        if (type == 0 && yearMasterActivityConfig.getInitUserGridConfig() != null) {
            yearMasterActivityConfig.getInitUserGridConfig().forEach((k, v) -> {
                list.get(k).setGridType(v);
            });
        }
        fillGrid(list);
        return list;
    }

    /**
     * 计算喜庆值 【喜庆值】=【基础喜庆值】*【模式倍数】
     * boss加成在跨服计算
     *
     * @param deleteList
     * @return
     */
    public static int getGridScore(List<GridDetail> deleteList, int mode) {

        int multiple = 1;
        if (mode == 0) {
            multiple = yearMasterActivityConfig.getNormalScoreMultiple();
        } else if (mode == 1) {
            multiple = yearMasterActivityConfig.getHighScoreMultiple();
        } else if (mode == 2) {
            multiple = yearMasterActivityConfig.getFastScoreMultiple();
        }

        int score = 0;
        score = yearMasterActivityConfig.getScoreMap().get(deleteList.size()) * multiple;

        /*for (GridDetail g : deleteList) {
            if (scoreMap.containsKey(g.getGridType())) {
                score += scoreMap.get(g.getGridType()) * multiple;
            }
        }*/
        return score;
    }

    private static void initGrid(List<GridDetail> list) {
        //补充大小
        int size = yearMasterActivityConfig.getRow() * yearMasterActivityConfig.getColumn();
        int listSize = list.size();
        if (listSize < size) {
            for (int i = 0; i < size - listSize; i++) {
                list.add(new GridDetail(-1));
            }
        }
    }

    /**
     * 填充格子
     *
     * @param list
     * @return 生产新格子的下标字符串   1|2|3
     */
    public static String fillGrid(List<GridDetail> list) {
        //logger.info("填充模块");

        StringBuffer resultStr = new StringBuffer();
        if (list == null) {
            list = new ArrayList<>();
        }

        initGrid(list);

        //printlnGridList(list);

        List<GridDetail> aroundIndexList = new ArrayList<>();

        Map<Integer, GridDetail> weightMap = new HashMap<>();


        for (int i = 0; i < list.size(); i++) {
            GridDetail gridDetail = list.get(i);
            if (gridDetail.getGridType() == -1) {
                //初始化新格子 找到周围的格子计算权重
                //直接相连 相隔
                fillAroundIndex(i, aroundIndexList, list);
                //计算权重
                fillWeightMap(weightMap, aroundIndexList);

                int index = i;
//                weightMap.forEach((k, v) -> {
//                    logger.info("index:" + index + "||weight：" + k + "_" + v.getWeight());
//                });
                //根据权重生产新格子
                gridDetail.setGridType(getRandomGridType(weightMap));

                if (resultStr.length() > 0) {
                    resultStr.append("|");
                }
                resultStr.append(i);
                //printlnGridList(list);
            }
        }
        return resultStr.toString();
    }


    private static void fillWeightMap(Map<Integer, GridDetail> weightMap, List<GridDetail> aroundIndexList) {
        //清理
        weightMap.clear();


        //周围格子影响权重
        aroundIndexList.forEach(gridDetail -> {
            if (!weightMap.containsKey(gridDetail.getGridType())) {
                weightMap.put(gridDetail.getGridType(), gridDetail);
            } else {
                GridDetail mapGrid = weightMap.get(gridDetail.getGridType());
                //叠加
                mapGrid.setWeight(mapGrid.getWeight() + gridDetail.getWeight());
            }

        });

        //增加基础格子配置权重
        yearMasterActivityConfig.getBaseGridWeightMap().values().forEach(gridDetail -> {
            if (!weightMap.containsKey(gridDetail.getGridType())) {
                GridDetail base = new GridDetail();
                base.setWeight(gridDetail.getWeight());
                base.setGridType(gridDetail.getGridType());
                weightMap.put(gridDetail.getGridType(), base);
            } else {
                GridDetail mapGrid = weightMap.get(gridDetail.getGridType());
                //叠加
                mapGrid.setWeight(mapGrid.getWeight() + gridDetail.getWeight());
            }
        });
    }


    private static void fillWeightGrid(int index, WeightReduceType weightType, List<GridDetail> linkIndexList, List<GridDetail> list) {
        GridDetail gridDetail = list.get(index);

        if (gridDetail != null && gridDetail.getGridType() != -1) {
            int weight = 0;
            GridDetail config = yearMasterActivityConfig.getBaseGridWeightMap().get(gridDetail.getGridType());
            switch (weightType) {
                case Link:
                    weight = config.getLinkReduce();
                    break;
                case Lean:
                    weight = config.getLeanReduce();
                    break;
                default:
                    break;
            }
            GridDetail copy = gridDetail.copy();
            //权重加减
            copy.setWeight(weight);
            linkIndexList.add(copy);
        }
    }

    /**
     * 获取周围格子 最多8个
     */
    private static void fillAroundIndex(int index, List<GridDetail> aroundIndexList, List<GridDetail> list) {
        aroundIndexList.clear();

        //上
        int i1 = index - yearMasterActivityConfig.getColumn();
        if (i1 >= 0) {
            fillWeightGrid(i1, WeightReduceType.Link, aroundIndexList, list);
            //上左
            if (!((i1 + 1) % yearMasterActivityConfig.getColumn() == 1)) {
                int li1 = i1 - 1;
                fillWeightGrid(li1, WeightReduceType.Lean, aroundIndexList, list);
            }

            //上右
            if (!((i1 + 1) % yearMasterActivityConfig.getColumn() == 0)) {
                int ri1 = i1 + 1;
                fillWeightGrid(ri1, WeightReduceType.Lean, aroundIndexList, list);
            }
        }
        //下
        int i2 = index + yearMasterActivityConfig.getColumn();
        if (i2 < yearMasterActivityConfig.getColumn() * yearMasterActivityConfig.getRow()) {
            fillWeightGrid(i2, WeightReduceType.Link, aroundIndexList, list);
            //下左
            if (!((i2 + 1) % yearMasterActivityConfig.getColumn() == 1)) {
                int li2 = i2 - 1;
                fillWeightGrid(li2, WeightReduceType.Lean, aroundIndexList, list);
            }
            //下右
            if (!((i1 + 1) % yearMasterActivityConfig.getColumn() == 0)) {
                int ri2 = i2 + 1;
                fillWeightGrid(ri2, WeightReduceType.Lean, aroundIndexList, list);
            }

        }
        //左
        if (!((index + 1) % yearMasterActivityConfig.getColumn() == 1)) {
            int i3 = index - 1;
            fillWeightGrid(i3, WeightReduceType.Link, aroundIndexList, list);
        }

        //右
        if (!((index + 1) % yearMasterActivityConfig.getColumn() == 0)) {
            int i4 = index + 1;
            fillWeightGrid(i4, WeightReduceType.Link, aroundIndexList, list);
        }
    }


    /**
     * 消除格子
     *
     * @param inlist
     * @param list
     * @return 消除后 格子的位移index  1;13|2;14
     */
    public static String changeGrid(List<Integer> inlist, List<GridDetail> list) {
        //logger.info("清除模块");
        //1 清除
        for (int index : inlist) {
            list.set(index, new GridDetail(-1));
        }

        //printlnGridList(list);

        //logger.info("平移模块");

        StringBuffer resultStr = new StringBuffer();
        //2 平移
        // 若被消除物件的【格子①】纵向存在未被消除物件【格子②】，且【格子②编号】>【格子①编号】则物件平移至【格子①】
        /*for (int i = 0; i < list.size(); i++) {
            GridDetail gridDetail = list.get(i);

            //需要处理的格子
            if (gridDetail.getGridType() == -1) {

                int currentIndex = i;
                int downIndex = i + yearMasterActivityConfig.getColumn();

                while (downIndex < list.size()) {
                    //下方是否有格子
                    GridDetail downGrid = list.get(downIndex);
                    if (downGrid != null && downGrid.getGridType() != -1) {
                        list.set(i, downGrid);
                        list.set(downIndex, gridDetail);
                        if (resultStr.length() > 0) {
                            resultStr.append("|");
                        }
                        resultStr.append(downIndex).append(";").append(currentIndex);
                        break;
                    }
                    downIndex += yearMasterActivityConfig.getColumn();
                }
            }
        }*/
        //改成反向
        for (int i = list.size() - 1; i >= 0; i--) {
            GridDetail gridDetail = list.get(i);

            //需要处理的格子
            if (gridDetail.getGridType() == -1) {

                int currentIndex = i;
                int downIndex = i - yearMasterActivityConfig.getColumn();

                while (downIndex >= 0) {
                    //下方是否有格子
                    GridDetail downGrid = list.get(downIndex);
                    if (downGrid != null && downGrid.getGridType() != -1) {
                        list.set(i, downGrid);
                        list.set(downIndex, gridDetail);
                        if (resultStr.length() > 0) {
                            resultStr.append("|");
                        }
                        resultStr.append(downIndex).append(";").append(currentIndex);
                        break;
                    }
                    downIndex -= yearMasterActivityConfig.getColumn();
                }
            }
        }

        //printlnGridList(list);

        return resultStr.toString();
    }



    /**
     * 根据权重获取格子类型
     *
     * @param weightMap
     * @return
     */
    private static int getRandomGridType(Map<Integer, GridDetail> weightMap) {
        if (weightMap == null || weightMap.size() == 0) {
            weightMap = yearMasterActivityConfig.getBaseGridWeightMap();
        }

        int sumWeight = 0;
        for (GridDetail gridDetail : weightMap.values()) {
            sumWeight += gridDetail.getWeight();
        }

        int randomValue = YearMasterMgr.getRandom().next(0, sumWeight);
        int tempWeight = 0;
        for (GridDetail gridDetail : weightMap.values()) {
            tempWeight += gridDetail.getWeight();
            if (tempWeight > randomValue) {
                //logger.info("random:" + randomValue + "||类型" + gridDetail.getGridType());
                return gridDetail.getGridType();
            }
        }


        return 0;
    }

    public static boolean checkGridType(List<Integer> inlist, List<GridDetail> list) {

        int type = -1;
        for (int index : inlist) {
            GridDetail gridDetail = list.get(index);
            if (gridDetail == null) {
                return false;
            }
            //初始化
            if (type == -1) {
                type = gridDetail.getGridType();
            }

            if (type != gridDetail.getGridType()) {
                return false;
            }
        }

        return true;
    }


    /**
     * 判断是否为正方形
     *
     * @param list
     * @return
     */
    public static boolean checkGridSquare(List<Integer> list) {

        int findNum = 0;
        for (int targetIndex : list) {
            for (int index : list) {
                if (index == targetIndex) {
                    continue;
                }
                int result = Math.abs(index - targetIndex);

                if (result == 1 || result == yearMasterActivityConfig.getColumn() || result == yearMasterActivityConfig.getColumn() - 1 || result == yearMasterActivityConfig.getColumn() + 1) {
                    findNum++;
                }
            }
            if (findNum != 3) {
                return false;
            }
            findNum = 0;
        }
        return true;
    }

    /**
     * 九桶消除
     * @param list
     * @return
     */
    public static boolean checkGridNineSquare(List<Integer> list) {
        list = new ArrayList<>(list);
        Collections.sort(list);
        int tempIndex = 0;
        int num = 0;
        for (int index : list) {
            num++;
            if(tempIndex != 0 && Math.abs(index - tempIndex) != 1){
                return false;
            }
            if(num % 3 == 0){
                tempIndex = index + yearMasterActivityConfig.getColumn() - 3;
            }else{
                tempIndex = index;
            }
        }
        return true;
    }

    /**
     * 16个正方形消除
     * @param list
     * @return
     */
    public static boolean checkGrid16Square(List<Integer> list) {
        list = new ArrayList<>(list);
        Collections.sort(list);
        int tempIndex = 0;
        int num = 0;
        for (int index : list) {
            num++;
            if(tempIndex != 0 && Math.abs(index - tempIndex) != 1){
                return false;
            }
            if(num % 4 == 0){
                tempIndex = index + yearMasterActivityConfig.getColumn() - 4;
            }else{
                tempIndex = index;
            }
        }
        return true;
    }


    /**
     * 判断格子两个格子是否相连
     *
     * @return
     */
    public static boolean checkGridLink(int curtIndex, int targetIndex) {
        int result = Math.abs(curtIndex - targetIndex);
        if ((curtIndex / yearMasterActivityConfig.getColumn() == targetIndex / yearMasterActivityConfig.getColumn()
                && result == 1)
                || result == yearMasterActivityConfig.getColumn()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean checkGridLink(int firstIndex, int secondIndex,int thirdIndex) {
        return checkGridLink(firstIndex,secondIndex) && checkGridLink(secondIndex,thirdIndex);
    }

    //是不是直线的消除
    public static boolean checkGridLink(List<Integer> indexList) {
        indexList = new ArrayList<>(indexList);
        Collections.sort(indexList);
        for(int i = 0;i < indexList.size() - 1;i++){
            if(!checkGridLink(indexList.get(i),indexList.get(i+1))){
                return false;
            }
        }
        return true;
    }

    private enum WeightReduceType {

        /*
              x
             xox
              x
       */
        Link,
        /*
              x x
               o
              x x
        */
        Lean

    }

    /**
     * 检查消除的下标是否正确
     *
     * @param indexList
     * @return
     */
    public static boolean checkGridIndex(List<Integer> indexList) {
        if (indexList != null && indexList.size() > 0) {

            HashSet<Integer> repeatSet = new HashSet<>();
            for (int index : indexList) {
                //下标超过范围
                if (index < 0 || index > yearMasterActivityConfig.getColumn() * yearMasterActivityConfig.getRow() - 1) {
                    return false;
                }
                repeatSet.add(index);
            }
            //重复下标
            if (repeatSet.size() != indexList.size()) {
                return false;
            }
        }
        return true;
    }

    //----------------------------------------------------------------调试-----------------------------------------------------------------
    public static void main(String[] args) {
        testGameLogic();
    }

    public static void testGameLogic() {

        yearMasterActivityConfig = new YearMasterActivityConfig();
        Map<Integer, Integer> scoreMap = new HashMap<>();
        scoreMap.put(1, 10);
        scoreMap.put(2, 40);
        scoreMap.put(4, 100);

        yearMasterActivityConfig.setScoreMap(scoreMap);

        Map<Integer, GridDetail> baseGridWeightMap = new HashMap<>();
        baseGridWeightMap.put(0, new GridDetail(0, 200, -40, -20));
        baseGridWeightMap.put(1, new GridDetail(1, 200, -40, -20));
        baseGridWeightMap.put(2, new GridDetail(2, 200, -40, -20));
        baseGridWeightMap.put(3, new GridDetail(3, 200, -40, -20));

        yearMasterActivityConfig.setBaseGridWeightMap(baseGridWeightMap);
        //初始格子
        Map<Integer, Integer> initUserGridConfig = new HashMap<>();
        int configGridType = 1;
        initUserGridConfig.put(0, configGridType);
        initUserGridConfig.put(1, configGridType);
        initUserGridConfig.put(2, configGridType);
        initUserGridConfig.put(3, configGridType);
        initUserGridConfig.put(4, configGridType);
        initUserGridConfig.put(8, configGridType);
        initUserGridConfig.put(9, configGridType);
        yearMasterActivityConfig.setInitUserGridConfig(initUserGridConfig);

        //0 根据权重初始化格子
        List<GridDetail> list = getConfigGridList(1);
        Scanner sc = new Scanner(System.in);
        while (true) {
            logger.debug("请输入消除id 间隔符,");
            String ids = sc.nextLine();

            String[] split = ids.split(",");

            List<Integer> inlist = new ArrayList<>();
            for (String s : split) {
                inlist.add(Integer.parseInt(s));
            }

            if (inlist.size() != 1 && inlist.size() != 2 && inlist.size() != 4) {
                continue;
            }
            if (inlist.size() > 1) {
                //1 判断是否格子相连
                if (inlist.size() == 2) {
                    boolean blink = checkGridLink(inlist.get(0), inlist.get(1));
                    logger.debug("link:" + blink);
                    if (!blink) {
                        continue;
                    }
                }
                //是否正方形
                if (inlist.size() == 4) {
                    boolean bSquare = checkGridSquare(inlist);
                    logger.debug("bSquare:" + bSquare);
                    if (!bSquare) {
                        continue;
                    }
                }

                //2 格子是否同种类
                boolean bType = checkGridType(inlist, list);
                logger.debug("bType:" + bType);
                if (!bType) {
                    continue;
                }
            }

            //3 改变格子
            changeGrid(inlist, list);

            //4 根据权重初始化格子
            fillGrid(list);

//            //分数
//            long deleteGridScore = getGridScore(deleteList, 1);
//            //printlnGridList(list);
//
//            logger.debug("deleteGridScore:" + deleteGridScore);
        }
    }

    public static void printlnGridList(List<GridDetail> list) {
        String debugString = "";
        for (int i = 0; i < list.size(); i++) {

            if (i != 0 && i % yearMasterActivityConfig.getColumn() == 0) {
                logger.info(debugString);
                debugString = "";
            }

            String a = "    ";
            if (i >= 10) {
                a = "   ";
            }

            debugString += "类型" + list.get(i).getGridType() + "-" + i + a;
            // System.out.print(list.get(i).getGridType() + "-" + i + a);

            if (i == list.size() - 1) {
                logger.info(debugString);
            }
        }
    }


}
